package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.AgeDomain;
import server.AlexaUpdate;
import server.GetPage;
import server.GooglePageRank;
import server.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;
import data.Memcache;

@SuppressWarnings("serial")
public class LinkInServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.getWriter().println("Hello, world");
        resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String name = Utils.fomatDomain(URLDecoder.decode(st.nextToken(),"UTF-8"));
		
		if(Utils.checkDomain(name))
		{
			DBCollection coll = Data.data("domain");
			DBObject domains = coll.findOne(new BasicDBObject("name",name));
		
			if(domains == null)
			{
				Random generator = new Random();
				int r = generator.nextInt(100000);
				DBObject domain = new BasicDBObject();
				domain.put("name", name);
				domain.put("update", new Date().getTime());
				domain.put("random", r);

				try {
					new GetPage(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GooglePageRank(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AgeDomain(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AlexaUpdate(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new Whois(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				try {
					Thread.sleep(10000);
					coll.save(domain);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Memcache.setMemcache("last-update", domain.get("name").toString());
				
				resp.sendRedirect("/link/"+name);
			} else {
				if(domains.get("possex") == null || domains.get("possex") != null && !domains.get("possex").toString().equals("1"))
				{
					DBCollection colls = Data.data("link");
					DBCursor inlink = colls.find(new BasicDBObject("link",name)).limit(20);
					req.setAttribute("inlink", inlink);
					req.setAttribute("domain", domains);
					req.setAttribute("linkin", "true");
					req.setAttribute("type", "in link");
					try {
						req.getRequestDispatcher("/link.jsp").forward(req, resp);
					} catch (ServletException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					resp.sendError(resp.SC_NOT_FOUND,"Content removed because our policy !");
				}
			}
		}
		try {
			req.getRequestDispatcher("/link.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
    }
		

}
